

package com.starbaba.apiActivity.view;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.base.common.database.BaseDao;
import com.base.common.exception.AppException;
import com.base.common.log.LogService;
import com.google.gson.JsonObject;
import com.opensymphony.xwork2.ModelDriven;
import com.starbaba.apiActivity.service.ApiActivityConfService;
import com.starbaba.common.ResultJson;
import com.starbaba.core.utils.PropertyParamMapBuilder;
import com.starbaba.core.utils.Struts2Utils;
import com.starbaba.core.utils.json.JsonUtils;
import com.starbaba.core.web.page.PageResponse;
import com.starbaba.core.web.struts2.BaseAction;
import com.starbaba.loanActivity.model.UserCommentModel;
import com.starbaba.model.dictionary.Constant;
import com.starbaba.model.utils.JSONUtils;
import com.starbaba.redis.JedisUtils;
import com.starbaba.system.user.model.UserVO;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiActivity;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelItem;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelItemBasis;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelItemOption;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelItemOptionBasis;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelPage;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelProject;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelType;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelValiRule;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiModelValidate;
import com.tuanzi.server.loan_base.model.db.apiModel.ApiThird;

@SuppressWarnings({"serial","unchecked","rawtypes","unused"})
public class ApiActivityConfAction extends BaseAction implements ModelDriven<ApiModelItemOptionBasis> {

	@SuppressWarnings("deprecation")
    private static BaseDao dao = new BaseDao(Constant.POOL_LIFE);
	
	private static final String COMM_REDIS_KEY = "loan:activity_comment_list_";   //评论列表在redis中key的前缀，跟loan_service中的获取活动评论列表要保持一致
	
	private ApiActivityConfService service;
	
	@Autowired
	@Qualifier("apiActivityConfServiceImpl")
	public void setService(ApiActivityConfService service) {
		this.service = service;
	}

	public String show(){
		return "success";
	}
	
	public void queryList(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		parsePageRequest();
		
		PageResponse pageResponse = new PageResponse();
		int start = pageRequest.getIDisplayStart();
		int length = pageRequest.getIDisplayLength();
		
		List list = service.getDateList(start, length, pageResponse, paramsMap);
		pageResponse.setAaData(list);

		try {
			sendJsonMessage(JsonUtils.toJson(pageResponse));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void deleteValiRule(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String valiRuleId = (String) paramsMap.get("valiRuleId");
		String deleteSql = "delete from loan_api_model_vali_rule where id = ?";
		JsonObject object = new JsonObject();
		try {
			dao.delete(deleteSql, new Object[]{valiRuleId});
			object.addProperty("success", 1);
			
		} catch (AppException e) {
			e.printStackTrace();
			object.addProperty("success", 0);
		}
		try {
			sendJsonMessage(JsonUtils.toJson(object));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	public void saveValiRule() throws AppException{
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String currTime = dateFormater.format(date);
		String itemId = (String) paramsMap.get("itemId");
		Integer index = Integer.valueOf((String) paramsMap.get("index"));
		
		for(int i = 1;i<=index;i++){
			String valiRuleId = (String) paramsMap.get("valiRuleId"+i);
			String validateId = (String) paramsMap.get("validateId"+i);
			if(validateId == null || "".equals(validateId)){
				continue;
			}
			String params = (String) paramsMap.get("params"+i);
			if(params == null || "".equals(params)){
				params = "";
			}
			String errorMsg = (String) paramsMap.get("errorMsg"+i);
			if(errorMsg == null || "".equals(errorMsg)){
				errorMsg = "";
			}
			ApiModelValiRule vali = new ApiModelValiRule();
			vali.setCreate_time(currTime);
			vali.setErrorMsg(errorMsg);
			vali.setParams(params);
			vali.setItem_id(Long.valueOf(itemId));
			vali.setUpdate_time(currTime);
			vali.setValidate_id(Long.valueOf(validateId));
			
			if(valiRuleId == null || "".equals(valiRuleId)){  //保存
				dao.add(vali);
			}else{ //更新
				String updateSql = "update loan_api_model_vali_rule set validate_id = ?,params = ?,errorMsg = ?,item_id = ?,update_time = ? where id = ?";
				dao.update(updateSql, new Object[]{validateId,params,errorMsg,itemId,currTime,valiRuleId});
			}
		}
		
		JsonObject object = new JsonObject();
		object.addProperty("success", 1);
		try {
			sendJsonMessage(JsonUtils.toJson(object));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//添加校验规则
	public String editValidate() throws AppException{
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String itemId = (String) paramsMap.get("itemId");
		paramsMap.put("itemId", itemId);
		
		//校验器
		String selValiSql = "select * from loan_api_model_validate";
		List<ApiModelValidate> valiList = dao.list(selValiSql, ApiModelValidate.class);
		String jsonVali = JSONUtils.toJsonString(valiList);
		paramsMap.put("jsonVali", jsonVali);
		paramsMap.put("valiList", valiList);
		
		//item下的校验规则
		String selRuleSql = "select * from loan_api_model_vali_rule r where r.item_id = ? ";
		List<ApiModelValiRule> ruleList = dao.list(selRuleSql, ApiModelValiRule.class, itemId);
		paramsMap.put("ruleList", ruleList);
		paramsMap.put("ruleCount", ruleList.size());
		
		return "success";
	}
	
	//复制API
	public String copyApi() throws AppException{
		HttpSession session = ServletActionContext.getRequest().getSession();
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String apiId = (String) paramsMap.get("apiId");
		UserVO user = getUserVO();
		String userName = user.getUsername();
		
		//获取所有甲方
		List<ApiThird> thirdList = getAllApiThird();
		paramsMap.put("thirdList", thirdList);
		
		//获取所有页面
		List<ApiModelPage> pageList = getAllPage();
		String jsonPage = JSONUtils.toJsonString(pageList);
		paramsMap.put("pageList", pageList);
		paramsMap.put("jsonPage", jsonPage);
		
		//获取所有栏目
		List<ApiModelProject> projList = getAllProject();
		String jsonProj = JSONUtils.toJsonString(projList);
		paramsMap.put("projList", projList);
		paramsMap.put("jsonProj", jsonProj);
		
		//获取所有通用item
		List<ApiModelItemBasis> itemBasisList = getAllItemBasis();
		String jsonItemBasis = JSONUtils.toJsonString(itemBasisList);
		paramsMap.put("itemBasisList", itemBasisList);
		paramsMap.put("jsonItemBasis", jsonItemBasis);
		
		//复制api
		ApiActivity apiActivity = copyApiByApiId(apiId,userName);
		List<ApiModelItem> itemList = copyAllItem(apiId,apiActivity.getId());
		String jsonItem = JSONUtils.toJsonString(itemList);
		paramsMap.put("itemList", itemList);
		paramsMap.put("itemCount", itemList.size());
		paramsMap.put("jsonItem", jsonItem);
		paramsMap.put("apiActivity", apiActivity);
		
		return "success";
	}
	
	//通过apiId复制，返回新复制的Api主键
	public ApiActivity copyApiByApiId(String apiId,String username) throws AppException{
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String currTime = dateFormater.format(date);
		
		String selectSql = "Select * From loan_api_activity api where api.id = ?";
		ApiActivity api = dao.get(selectSql, ApiActivity.class, apiId);
		api.setId(null);
		api.setUser_name(username);
		api.setCtime(currTime);
		api.setUptime(currTime);
		Long newApiId = dao.addReturnGeneratedKey(api);
		api.setId(newApiId);
		return api;
	}
	
	//复制所有一级项
	private List<ApiModelItem> copyAllItem(String oldApiId,Long newApiId) throws AppException{
		String selectSql = "SELECT i.api_id,i.default_value,i.have_parent,i.id,i.item_basis_id,i.necessary,i.page_id,"
				+ "i.parent_item_id,i.partner_key,i.placeholder,i.sort,b.title "
				+ "FROM loan_api_model_item i,loan_api_model_itembasis b WHERE i.item_basis_id = b.id AND i.api_id = ? ORDER BY i.sort";
		List<ApiModelItem> itemList = dao.list(selectSql, ApiModelItem.class,oldApiId);
		if(itemList == null || itemList.size() == 0){
			return null;
		}
		
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String currTime = dateFormater.format(date);
		
		setParentItem(itemList,newApiId);
		for(ApiModelItem item:itemList){
			Long itemId = item.getId();
			
			//复制item
			item.setId(null);
			item.setApi_id(newApiId);
			item.setCreate_time(currTime);
			item.setUpdate_time(currTime);
			Long newItemId = dao.addReturnGeneratedKeyLong(item);
			item.setId(newItemId);
			
			//复制option
			copyOptionOfItem(itemId,newItemId);
			
			//复制校验规则
			copyValiRuleOfItem(itemId,newItemId);
		}
		itemList = dao.list(selectSql, ApiModelItem.class,newApiId);
		return itemList;
	}
	
	//复制校验规则
	public void copyValiRuleOfItem(Long oldItemId,Long newItemId) throws AppException{
		String selectSql = "select * from loan_api_model_vali_rule where item_id = ?";
		List<ApiModelValiRule> valiList = dao.list(selectSql, ApiModelValiRule.class, oldItemId);
		if(valiList == null || valiList.size() == 0){
			return;
		}
		for(ApiModelValiRule vali : valiList){
			vali.setId(null);
			vali.setItem_id(newItemId);
			dao.add(vali);
		}
	}
	
	//对带有指定父项的item先进行另外保存，获得测试itemId和正式itemId的映射
	public void setParentItem(List<ApiModelItem> itemList,Long newApiId) throws AppException{
		Map<Long,Long> map = new HashMap<Long, Long>();  //存储旧父itemId和新父itemId的映射关系
		int count = itemList.size();
		for(int i=0;i<count;i++){
			ApiModelItem item = itemList.get(i);
			Integer haveParent = item.getHave_parent();
			if(haveParent == 1){
				Long oldParentItemId = item.getParent_item_id();  
				Long newParentItemId = null;  //新的父itemId
				if(map.containsKey(oldParentItemId)){
					newParentItemId = map.get(oldParentItemId);
				}else{
					newParentItemId = saveParentItem(oldParentItemId,itemList,newApiId);
					map.put(oldParentItemId, newParentItemId);
					i--;
					count--;
				}
				item.setParent_item_id(newParentItemId);
			}
		}
	}
	
	//先保存父item
	public Long saveParentItem(Long parentItemId,List<ApiModelItem> itemList,Long newApiId) throws AppException{
		Long newItemId = 0l;
		for(ApiModelItem item:itemList){
			Long itemId = item.getId();
			if(itemId.longValue() == parentItemId){
				item.setId(null);
				item.setApi_id(newApiId);
				newItemId = dao.addReturnGeneratedKey(item);
				itemList.remove(item); //保存后删除对应的元素
				break;
			}
		}
		return newItemId;
	}
	
	//复制option
	public void copyOptionOfItem(Long oldItemId,Long newItemId) throws AppException{
		String selectSql = "select * from loan_api_model_item_option where item_id = ? order by sort";
		List<ApiModelItemOption> optionList = dao.list(selectSql, ApiModelItemOption.class, oldItemId);
		if(optionList == null || optionList.size() == 0){
			return;
		}
		for(ApiModelItemOption option : optionList){
			option.setId(null);
			option.setItem_id(newItemId);
			dao.add(option);
		}
		
	}
	
	public void deleteApi(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		JsonObject object = new JsonObject();
		String apiId = (String) paramsMap.get("apiId");
		String selectItemsSql = "select * from loan_api_model_item where api_id = ?";
		String deleteOptionSql = "delete from loan_api_model_item_option where item_id = ?";
		String deleteValiRuleSql = "delete from loan_api_model_vali_rule where item_id = ?";
		String deleteItemSql = "delete from loan_api_model_item where api_id = ?";
		String deleteApiSql = "delete from loan_api_activity where id = ?";
		List<ApiModelItem> itemList = null;
		try {
			itemList = dao.list(selectItemsSql, ApiModelItem.class, apiId);
		} catch (AppException e) {
			e.printStackTrace();
			object.addProperty("success", -1);
		}
		try {
			for(ApiModelItem item:itemList){
				Long itemId = item.getId();
				dao.delete(deleteOptionSql, new Object[]{itemId});
				dao.delete(deleteValiRuleSql, new Object[]{itemId});
			}
			dao.delete(deleteItemSql, new Object[]{apiId});
			dao.delete(deleteApiSql, new Object[]{apiId});
			object.addProperty("success", 1);
		} catch (AppException e) {
			e.printStackTrace();
			object.addProperty("success", -1);
		}
		try {
			sendJsonMessage(JsonUtils.toJson(object));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	//修改状态
	public void updateStatus(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		JsonObject object = new JsonObject();
		String apiId = (String) paramsMap.get("apiId");
		String status = (String) paramsMap.get("status");  
		String userName = (String) paramsMap.get("userName");
		String updateSql = "update loan_api_activity set status = ?,user_name = ? where id = ?";
		try {
			dao.update(updateSql, new Object[]{status,userName,apiId});
			object.addProperty("success", 1);
		} catch (AppException e) {
			e.printStackTrace();
			object.addProperty("success", -1);
		}
		try {
			sendJsonMessage(JsonUtils.toJson(object));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//删除一级项和所有对应的二级子项
	public void deleteApiItem(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		JsonObject object = new JsonObject();
		String itemId = (String) paramsMap.get("itemId");
		String apiId = (String) paramsMap.get("apiId");
		String userName = (String) paramsMap.get("userName");
		String deleteOptionSql = "delete from loan_api_model_item_option where item_id = ?";
		String deleteValiRuleSql = "delete from loan_api_model_vali_rule where item_id = ?";
		String deleteItemSql = "delete from loan_api_model_item where id = ?";
		try {
			dao.delete(deleteOptionSql, new Object[]{itemId});
			dao.delete(deleteValiRuleSql, new Object[]{itemId});
			dao.delete(deleteItemSql, new Object[]{itemId});
			
			if(StringUtils.isNotEmpty(apiId)){
				ApiActivity api = new ApiActivity();
				api.setId(Long.valueOf(apiId));
				api.setUser_name(userName);
				dao.update(api, "id");
			}
			
			object.addProperty("success", 1);
		} catch (AppException e) {
			LogService.error(e);
			object.addProperty("success", -1);
		}
		try {
			sendJsonMessage(JsonUtils.toJson(object));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void deleteItemOption(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		JsonObject object = new JsonObject();
		String optionId = (String) paramsMap.get("optionId");
		String deleteSql = "delete from loan_api_model_item_option where id = ?";
		try {
			dao.delete(deleteSql, new Object[]{optionId});
			object.addProperty("success", 1);
		} catch (AppException e) {
			e.printStackTrace();
			object.addProperty("success", -1);
		}
		try {
			sendJsonMessage(JsonUtils.toJson(object));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//保存所有二级子项
	public void saveOptions(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		JsonObject object = new JsonObject();
		
		String itemId = (String) paramsMap.get("itemId");
		Integer index = Integer.valueOf((String) paramsMap.get("index"));
		if(index == null || index == 0){
			object.addProperty("success", 0);
		}
		ApiModelItemOption option = new ApiModelItemOption();
		try {
			for(int i=1;i<=index;i++){
				String optionId = (String) paramsMap.get("optionId"+i);
				String sort = (String) paramsMap.get("sort"+i);
				String optionBasisId = (String) paramsMap.get("optionBasisId"+i);
				String showSon = (String) paramsMap.get("show_son"+i);
				if(sort == null || "".equals(sort) || optionBasisId == null || "".equals(optionBasisId)){
					continue;
				}
				if(showSon == null || "".equals(showSon)){
					showSon = "0";
				}
				if(optionId == null){
					option.setId(null);
				}else{
					option.setId(Long.valueOf(optionId));
				}
				option.setItem_id(Long.valueOf(itemId));
				option.setOption_basis_id(Long.valueOf(optionBasisId));
				option.setSort(Integer.valueOf(sort));
				option.setShow_son(Integer.valueOf(showSon));
				addOption(option);
			}
			object.addProperty("success", 1);
		} catch (AppException e) {
			e.printStackTrace();
			object.addProperty("success", -1);
		}
		try {
			sendJsonMessage(JsonUtils.toJson(object));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//保存二级子项
	public void addOption(ApiModelItemOption option) throws AppException{
		Long optionId = option.getId();
		if(optionId == null || optionId == 0){  //新增
			dao.add(option);
		}else{ //更新
			String updateSql = "update loan_api_model_item_option set item_id = ?,option_basis_id = ?,sort = ?,show_son = ? where id = ?";
			dao.update(updateSql, option.getItem_id(),option.getOption_basis_id(),option.getSort(),option.getShow_son(),option.getId());
		}
	}
	
	public String editOption() throws AppException{
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String itemId = (String) paramsMap.get("itemId");
		if(itemId == null || "".equals(itemId)){
			return "error";
		}
		String selectSql = "select * from loan_api_model_item where id = ? ";
		ApiModelItem item = dao.get(selectSql, ApiModelItem.class, itemId);
		paramsMap.put("item", item);
		
		//获取一级项的所有通用二级子项
		Long itemBasisId = item.getItem_basis_id();
		List<ApiModelItemOptionBasis> optionBasisList = getOptionBasisList(itemBasisId);
		String jsonBasisOption = JSONUtils.toJsonString(optionBasisList);
		paramsMap.put("optionBasisList", optionBasisList);
		paramsMap.put("jsonBasisOption", jsonBasisOption);
		
		//获取一级项的所有特殊二级子项
		List<ApiModelItemOption> optionList = getOptionList(itemId);
		String jsonOption = JSONUtils.toJsonString(optionList);
		paramsMap.put("optionList", optionList);
		paramsMap.put("jsonOption", jsonOption);
		
		paramsMap.put("optionCount", optionList.size());
		
		return "success";
	}
	
	//获取一级项的特殊option
	public List<ApiModelItemOption> getOptionList(String itemId) throws AppException{
		String selectSql = "select * from loan_api_model_item_option where item_id = ? order by sort";
		List<ApiModelItemOption> optionList = dao.list(selectSql, ApiModelItemOption.class, itemId);
		if(optionList == null){
			optionList = new ArrayList<ApiModelItemOption>();
		}
		return optionList;
	}
	
	//获得一级项的所有通用子项
	private List<ApiModelItemOptionBasis> getOptionBasisList(Long itemBasisId) throws AppException{
		String selectSql = "select * from loan_api_model_item_optionbasis where itembasis_id = ? ";
		List<ApiModelItemOptionBasis> list = dao.list(selectSql, ApiModelItemOptionBasis.class, itemBasisId);
		if(list == null){
			list = new ArrayList<ApiModelItemOptionBasis>();
		}
		return list;
	}
	
	//保存全部item
	public void saveAllItems(){
		
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String currTime = dateFormater.format(date);
		JsonObject object = new JsonObject();
		
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		Integer index = Integer.valueOf((String) paramsMap.get("index"));
		String userName = (String)paramsMap.get("userName");
		Long apiId = null;
		try {
			//保存Api
			apiId = saveApi(paramsMap);
		} catch (AppException e) {
			e.printStackTrace();
		}
		
		try {
			if(index != null && index != 0){
				ApiModelItem item = null;
				for(int i=1;i<=index;i++){
					String itemId = (String) paramsMap.get("itemId"+i);
					String pageId = (String) paramsMap.get("page_id"+i);
					String parentItemId = (String) paramsMap.get("parent_item_id"+i);
					String necessary = (String) paramsMap.get("necessary"+i);
					String sort = (String) paramsMap.get("sort"+i);
					String itemBasisId = (String) paramsMap.get("itemBasisId"+i);
					if(pageId == null || sort == null || itemBasisId == null){  //如果这些值为空，跳过
						continue;
					}
					String partnerKey = (String) paramsMap.get("partner_key"+i);
					if(StringUtils.isEmpty(partnerKey)){
						partnerKey = "";
					}
					String haveParent = "";
					if("0".equals(parentItemId)){
						haveParent = "0";
					}else{
						haveParent = "1";
					}
					String placeholder = (String) paramsMap.get("placeholder"+i);
					if(placeholder == null){
						placeholder = "";
					}
					String defaultValue = (String) paramsMap.get("default_value"+i);
					if(defaultValue == null){
						defaultValue = "";
					}
					item = new ApiModelItem();
					if(itemId != null && !"0".equals(itemId)){
						item.setId(Long.valueOf(itemId));
					}
					item.setCreate_time(currTime);
					item.setSort(Integer.valueOf(sort));
					item.setPartner_key(partnerKey);
					item.setPlaceholder(placeholder);
					item.setPage_id(Integer.valueOf(pageId));
					item.setParent_item_id(Long.valueOf(parentItemId));
					item.setHave_parent(Integer.valueOf(haveParent));
					item.setNecessary(Integer.valueOf(necessary));
					item.setItem_basis_id(Long.valueOf(itemBasisId));
					item.setDefault_value(defaultValue);
					item.setUpdate_time(currTime);
					item.setApi_id(apiId);
					item.setUserName(userName);
					Long newItemId = addItem(item);
				}
			}
			object.addProperty("success", 1);
		} catch (AppException e) {
			e.printStackTrace();
			object.addProperty("success", -1);
		}
		try {
			sendJsonMessage(JsonUtils.toJson(object));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//新增或者编辑API
	public String editApi() throws AppException{
		
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String apiId = (String) paramsMap.get("apiId");
		
		//获取所有甲方
		List<ApiThird> thirdList = getAllApiThird();
		paramsMap.put("thirdList", thirdList);
		
		//获取所有页面
		List<ApiModelPage> pageList = getAllPage();
		String jsonPage = JSONUtils.toJsonString(pageList);
		paramsMap.put("pageList", pageList);
		paramsMap.put("jsonPage", jsonPage);
		
		//获取所有栏目
		List<ApiModelProject> projList = getAllProject();
		String jsonProj = JSONUtils.toJsonString(projList);
		paramsMap.put("projList", projList);
		paramsMap.put("jsonProj", jsonProj);
		
		//获取所有item
		List<ApiModelItem> itemList = getAllItem(apiId);
		String jsonItem = JSONUtils.toJsonString(itemList);
		paramsMap.put("itemList", itemList);
		paramsMap.put("jsonItem", jsonItem);
		
		//获取所有通用item
		List<ApiModelItemBasis> itemBasisList = getAllItemBasis();
		String jsonItemBasis = JSONUtils.toJsonString(itemBasisList);
		paramsMap.put("itemBasisList", itemBasisList);
		paramsMap.put("jsonItemBasis", jsonItemBasis);
		
		if(apiId == null || "".equals(apiId) || "0".equals(apiId)){  //新增
			
		}else{  //更新
			String apiSelectSql = "SELECT * FROM loan_api_activity a WHERE a.id = ?";
			ApiActivity apiActivity = dao.get(apiSelectSql, ApiActivity.class, apiId);
			paramsMap.put("apiActivity", apiActivity);
			paramsMap.put("itemCount", itemList.size());
			
		}
		
		return "success";
	}
	
	//保存Api
	public Long saveApi(Map<String, Object> paramsMap) throws AppException{
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String currTime = dateFormater.format(date);
		
		String apiId = (String) paramsMap.get("apiId");
		String apiName = (String) paramsMap.get("apiName");
		String thirdId = (String) paramsMap.get("thirdId");
		String userName = (String) paramsMap.get("userName");
		ApiThird apiThird = null;
		if(StringUtils.isEmpty(thirdId) || thirdId.length() == 0){
			apiThird = new ApiThird();
			apiThird.setThird_id(-1L);
			apiThird.setThird_name("");
		}else{
			apiThird = getApiThirdByThirdId(thirdId);
		}
		
		if(apiId == null || "".equals(apiId)){  //保存API
			ApiActivity api = new ApiActivity();
			api.setApi_name(apiName);
			api.setThird_id(apiThird.getThird_id());
			api.setThird_name(apiThird.getThird_name());
			api.setCtime(currTime);
			api.setUptime(currTime);
			api.setUser_name(userName);
			Long id = dao.addReturnGeneratedKey(api);
			return id;
		}else{  //更新API
			String updateSql = "update loan_api_activity set api_name = ? ,third_id = ?,third_name = ?,uptime = ?,user_name = ? where id = ?";
			dao.update(updateSql, new Object[]{apiName,apiThird.getThird_id(),apiThird.getThird_name(),currTime,userName,apiId});
			return Long.valueOf(apiId);
		}
	}
	
	//保存单项选项
	public void saveItem() throws AppException{
		
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String currTime = dateFormater.format(date);
		
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		JsonObject object = new JsonObject();
		
		//保存Api:保存item前，要先确认是否已保存Api
		Long apiId = saveApi(paramsMap);
		object.addProperty("apiId", apiId);
		
		//更新或保存item
		try {
			String itemId = (String) paramsMap.get("itemId");
			String pageId = (String) paramsMap.get("pageId");
			String parentItemId = (String) paramsMap.get("parentItemId");
			String necessary = (String) paramsMap.get("necessary");
			String sort = (String) paramsMap.get("sort");
			String itemBasisId = (String) paramsMap.get("itemBasisId");
			String partnerKey = (String) paramsMap.get("partnerKey");
			String userName = (String) paramsMap.get("userName");
			if(partnerKey == null){
				partnerKey = "";
			}
			String haveParent = "";
			if("0".equals(parentItemId)){
				haveParent = "0";
			}else{
				haveParent = "1";
			}
			String placeholder = (String) paramsMap.get("placeholder");
			if(placeholder == null){
				placeholder = "";
			}
			String defaultValue = (String) paramsMap.get("defaultValue");
			if(defaultValue == null){
				defaultValue = "";
			}
			
			ApiModelItem item = new ApiModelItem();
			if(itemId != null && !"0".equals(itemId)){
				item.setId(Long.valueOf(itemId));
			}
			item.setCreate_time(currTime);
			item.setSort(Integer.valueOf(sort));
			item.setPartner_key(partnerKey);
			item.setPlaceholder(placeholder);
			item.setPage_id(Integer.valueOf(pageId));
			item.setParent_item_id(Long.valueOf(parentItemId));
			item.setHave_parent(Integer.valueOf(haveParent));
			item.setNecessary(Integer.valueOf(necessary));
			item.setItem_basis_id(Long.valueOf(itemBasisId));
			item.setDefault_value(defaultValue);
			item.setUpdate_time(currTime);
			item.setUserName(userName);
			item.setApi_id(apiId);
			Long newItemId = addItem(item);
			object.addProperty("itemId", newItemId);
			object.addProperty("success", 1);
		} catch (AppException e) {
			e.printStackTrace();
			object.addProperty("success", -1);
		}
		try {
			sendJsonMessage(JsonUtils.toJson(object));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//新增或者更新item
	private Long addItem(ApiModelItem item) throws AppException{
		Long itemId = item.getId();
		if(itemId == null || itemId == 0){  //保存item
			itemId = dao.addReturnGeneratedKey(item);
		}else{
			String updateSql = "update loan_api_model_item "
					+ "set page_id = ?,parent_item_id = ?,necessary = ?,item_basis_id = ?,"
					+ "default_value = ?,sort = ?,partner_key = ?,placeholder = ?,update_time = ?,api_id = ? "
					+ "where id = ?";
			dao.update(updateSql,item.getPage_id(),item.getParent_item_id(),item.getNecessary(),
					item.getItem_basis_id(),item.getDefault_value(),item.getSort(),item.getPartner_key(),item.getPlaceholder(),
					item.getCreate_time(),item.getApi_id(),itemId);
		}
		
		ApiActivity api = new ApiActivity();
		api.setId(item.getApi_id());
		api.setUser_name(item.getUserName());
		dao.update(api, "id");
		
		return itemId;
	}
	
	/**
	 * 通过甲方ID获取甲方
	 * @param thirdId
	 * @return
	 * @throws AppException
	 */
	public ApiThird getApiThirdByThirdId(String thirdId) throws AppException{
		String selectSql = "SELECT * FROM loan_api_third t where t.third_id = ?";
		return dao.get(selectSql, ApiThird.class, thirdId);
	}
	
	/**
	 * 获得全部甲方
	 * @return
	 * @throws AppException 
	 */
	private List<ApiThird> getAllApiThird() throws AppException{
		String selectSql = "SELECT * FROM loan_api_third t";
		List<ApiThird> thirdList = dao.list(selectSql, ApiThird.class);
		return thirdList;
	}
	
	
	private List<ApiModelPage> getAllPage() throws AppException{
		String selectSql = "SELECT * FROM loan_api_model_page p";
		List<ApiModelPage> pageList = dao.list(selectSql, ApiModelPage.class);
		return pageList;
	}
	
	private List<ApiModelProject> getAllProject() throws AppException{
		String selectSql = "SELECT * FROM loan_api_model_project p";
		List<ApiModelProject> projList = dao.list(selectSql, ApiModelProject.class);
		return projList;
	}
	
	private List<ApiModelItem> getAllItem(String apiId) throws AppException{
		if(apiId == null || "".equals(apiId)){
			return new ArrayList<ApiModelItem>();
		}
		String selectSql = "SELECT i.api_id,i.default_value,i.have_parent,i.id,i.item_basis_id,i.necessary,i.page_id,"
				+ "i.parent_item_id,i.partner_key,i.placeholder,i.sort,b.title "
				+ "FROM loan_api_model_item i,loan_api_model_itembasis b WHERE i.item_basis_id = b.id AND i.api_id = ? ORDER BY i.sort";
		List<ApiModelItem> itemList = dao.list(selectSql, ApiModelItem.class,apiId);
		return itemList;
	}
	
	private List<ApiModelItemBasis> getAllItemBasis() throws AppException{
		String selectSql = "SELECT * FROM loan_api_model_itembasis i ";
		List<ApiModelItemBasis> itemBasisList = dao.list(selectSql, ApiModelItemBasis.class);
		if(itemBasisList == null){
			return new ArrayList<ApiModelItemBasis>();
		}
		return itemBasisList;
	}
	
	//获取模板类型
	public void getTypeList() throws AppException{
		String sql = "SELECT * FROM loan_api_model_type t";
		List<ApiModelType> typeList = dao.list(sql, ApiModelType.class);
		JsonObject object = new JsonObject();
		String jsonStr = JSONUtils.toJsonString(typeList);
		object.addProperty("typeList", jsonStr);
		try {
			sendJsonMessage(JsonUtils.toJson(object));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void updateType(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String itemId = (String) paramsMap.get("itemId");
		String typeId = (String) paramsMap.get("typeId");
		String updateSql = "UPDATE loan_api_model_itembasis SET type_id = ?,update_time = ? WHERE id = ?";
		try {
			dao.update(updateSql, new Object[]{typeId,new Date(),itemId});
			responseSuccess();
		} catch (AppException e) {
			e.printStackTrace();
			responseError(e);
		}
	}
	
	public void updateTitle(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String itemId = (String) paramsMap.get("itemId");
		String title = (String) paramsMap.get("title");
		String updateSql = "UPDATE loan_api_model_itembasis SET title = ?,update_time = ? WHERE id = ?";
		try {
			dao.update(updateSql, new Object[]{title,new Date(),itemId});
			responseSuccess();
		} catch (AppException e) {
			e.printStackTrace();
			responseError(e);
		}
	}
	
	public void updateDataKey(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String itemId = (String) paramsMap.get("itemId");
		String dataKey = (String) paramsMap.get("dataKey");
		String updateSql = "UPDATE loan_api_model_itembasis SET data_key = ?,update_time = ? WHERE id = ?";
		try {
			dao.update(updateSql, new Object[]{dataKey,new Date(),itemId});
			responseSuccess();
		} catch (AppException e) {
			e.printStackTrace();
			responseError(e);
		}
	}
	
	//编辑二级项页面
	public String editSecond() throws AppException{
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String itemId = (String) paramsMap.get("itemId");
		String selectSql = "SELECT * FROM loan_api_model_itembasis ib WHERE id = ?";
		String listSql = "SELECT * FROM loan_api_model_item_optionbasis io WHERE io.itembasis_id = ?";
		ApiModelItemBasis item = dao.get(selectSql, ApiModelItemBasis.class, itemId);
		paramsMap.put("item", item);
		List<ApiModelItemOptionBasis> optionList = dao.list(listSql, ApiModelItemOptionBasis.class, itemId);
		paramsMap.put("optionList", optionList);
		paramsMap.put("optionCount", optionList.size());
		return "success";
	}
	
	public void saveOptionList() throws AppException{
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		
		SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = new Date();
		String currTime = dateFormater.format(date);
		
		Integer index = Integer.valueOf((String) paramsMap.get("index"));
		String itemId = (String) paramsMap.get("itemId");
		if(index != null && index != 0){
			for(int i=1;i<=index;i++){  //循环保存每个option
				String optionId = (String) paramsMap.get("optionId"+i);
				String optionValue = (String) paramsMap.get("optionValue"+i);
				String optionKey = (String) paramsMap.get("optionKey"+i);
				if(optionValue == null || "".equals(optionValue)){
					continue;
				}
				if(optionKey == null || "".equals(optionKey)){
					continue;
				}
				if(optionId == null || "".equals(optionId)){  //保存
					ApiModelItemOptionBasis option =  new ApiModelItemOptionBasis();
					option.setItembasis_id(Long.valueOf(itemId));
					option.setOption_key(optionKey);
					option.setOption_value(optionValue);
					option.setCreate_time(currTime);
					option.setUpdate_time(currTime);
					dao.add(option);
				}else{  //更新
					String updateSql = "UPDATE loan_api_model_item_optionbasis SET option_key = ?,option_value = ? ,update_time = ? WHERE id = ?";
					dao.update(updateSql, new Object[]{optionKey,optionValue,currTime,optionId});
				}
			}
		}
		
		responseSuccess();
	}
	
	public void deleteItem(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String itemId = (String) paramsMap.get("itemId");
		try {
			if(itemId!=null && !"".equals(itemId)){
				String deleteOption = "DELETE FROM loan_api_model_item_optionbasis WHERE itembasis_id = ?";
				String deleteItem = "DELETE FROM loan_api_model_itembasis WHERE id = ?";
				dao.delete(deleteOption, new Object[]{itemId});
				dao.delete(deleteItem, new Object[]{itemId});
				responseSuccess();
			}
		} catch (AppException e) {
			e.printStackTrace();
			responseError(e);
		}
	}
	
	public void deleteOption(){
		paramsMap = PropertyParamMapBuilder.buildFromHttpRequest(Struts2Utils.getRequest(), paramsMap);
		String optionId = (String) paramsMap.get("optionId");
		try {
			if(optionId!=null && !"".equals(optionId)){
				String deleteSql = "DELETE FROM loan_api_model_item_optionbasis WHERE id = ?";
				dao.delete(deleteSql, new Object[]{optionId});
				responseSuccess();
			}
		} catch (AppException e) {
			e.printStackTrace();
			responseError(e);
		}
	}
	
	
	private void responseSuccess() {
		JsonObject result = new JsonObject();
		result.add("result", new ResultJson().toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 
	 *
	 * @Title responseSuccess
	 * @Description <p>
	 *              返回错误信息
	 *              </p>
	 *              　　　　　
	 * @author zhengjunjie
	 * @dateTime 2015年10月16日 下午2:26:53
	 *
	 */
	private void responseError(Exception error) {
		StringWriter writer = new StringWriter();
		error.printStackTrace(new PrintWriter(writer, true));
		ResultJson resultJson = new ResultJson(-2, 0, writer.toString());
		JsonObject result = new JsonObject();
		result.add("result", resultJson.toJSON());
		try {
			sendJsonMessage(result.toString());
		} catch (Exception e) {
			LogService.error(e);
		}
	}

	//删除缓存
	public void deleteCommInRedis(String commentId,String activityId) throws AppException{
		if(activityId == null || "".equals(activityId)){ //如果活动id为空，需要获取活动id
			String selectSql = "SELECT * FROM loan_user_comment c WHERE c.id = ?";
			UserCommentModel comm = dao.get(selectSql, UserCommentModel.class, commentId);
			if(comm == null){
				return;
			}
			activityId = comm.getActivity_id()+"";
		}
		String redisKey = COMM_REDIS_KEY+activityId;
		JedisUtils.del(redisKey);
	}
	
	@Override
	public ApiModelItemOptionBasis getModel() {
		
		return null;
	}

}
















